/**
 * 规则新增组件
 */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Input, Row, Col, Button, Icon } from 'antd';

const styles = {
	input: {
		display: 'inline-block',
		width: '9em'
	},
	icon: {
		marginRight: '.5em'
	},
	label: {
		marginLeft: '14px'
	},
	li: {
		marginBottom: '5px'
	}
};

class RuleEdit extends Component {
	constructor(props, context) {
		super(props, context);

		this.defaultState = {
			rules: [
				{ name: '免费', unit: 0 },
			]
		};

		this.state = { ...this.defaultState };
		if (props.rules && props.rules.length) {
			this.state.rules = props.rules;
		}
	}

	componentWillReceiveProps(nextProps) {
		if (this.props.visible && !nextProps.visible) this.setState({ ...this.defaultState });
	}

	getRules() {
		return this.state.rules;
	}

	add = () => {
		this.setState({
			rules: this.state.rules.concat({ name: '', unit: '' })
		});
	}

	remove(index) {
		this.setState({
			rules: this.state.rules.filter((r, i) => i !== index)
		});
	}

	ruleChange(e, index) {
		const { name, value } = e.target;
		const rules = this.state.rules.map((r, i) => i === index ? { ...r, [name]: value } : r);
		this.setState({ rules });
	}

	renderRule() {
		return this.state.rules.map((r, i) => (
			r.unit === 0 ? <li>{r.name}</li> :
			<li style={styles.li}>
				<Icon
					type="minus-circle-o"
					className="cursor"
					onClick={() => this.remove(i)}
					style={styles.icon}
				/>
				<Input
					name="name"
					value={r.name}
					placeholder="请输入品类名称"
					style={styles.input}
					onChange={e => this.ruleChange(e, i)}
				/>
				<label style={styles.label}>单位：</label>
				<Input
					name="unit"
					value={r.unit}
					placeholder="请输入单位"
					style={styles.input}
					onChange={e => this.ruleChange(e, i)}
				/>
			</li>
		));
	}

	render() {
		const { style } = this.props;
		return (
			<div style={style}>
				<ul>{this.renderRule()}</ul>
				<Button onClick={this.add}icon="plus" className="opt-but">添加</Button>
			</div>
		);
	}
}

RuleEdit.propTypes = {

};

export default RuleEdit;
